
Ext.define('designer.objects.Tree',{
	extend:'Ext.Panel',
	controllerUrl:'',
	litsType:'visual',	
	layout:'fit',
	initComponent:function(){
		
		this.dataStore = Ext.create('Ext.data.TreeStore',{
			proxy: {
			        type: 'ajax',
			    	url:this.controllerUrl + 'list',
			    	extraParams:{
			    		type:this.litsType
			    	},
			    	reader: {
			            type: 'json',
			            idProperty: 'id'
			        }
			},
			fields: [
			         {name:'id' ,  type:'string'},
			         {name:'text' , type:'string'},
			         {name:'objClass',type:'string'}
			     ],
			root: {
			        text: '/',
			        expanded: true,
			        id:0
			},
			autoLoad:false
		});
		
		this.treePanel = Ext.create('Ext.tree.Panel',{
			store:this.dataStore,
		    rootVisible:true,
		    useArrows: true,
		    viewConfig:{
		    	plugins: {
			            ptype: 'treeviewdragdrop'
			    },
			    listeners:{
					drop:{
						fn:this.sortChanged,
						scope:this
					}
				}
			}
		});
		
		this.treePanel.on('itemdblclick',function(view, record, element , index , e , eOpts){
			this.fireEvent('itemSelected' , record.get('id') , record.get('objClass'), record.get('text'));
		},this);
		
		this.items = [this.treePanel];
		this.callParent(arguments);
		this.addEvents(
	            /**
	             * @event dataSaved
	             * @param id
	             * @param className
	             * @param title
	             */
	           'itemSelected'
	    ); 
	},
	getStore:function(){
		return this.dataStore;
	},
	sortChanged:function( node, data, overModel,  dropPosition, options)
	{
		var parentId = 0;
		var parentNode = null;
		if(dropPosition == 'append'){
			parentId = overModel.get('id');
			parentNode = overModel;
		}else{
			parentId = overModel.parentNode.get('id');
			parentNode = overModel.parentNode;
		}
		var view = this.treePanel.getView();			
		var childsOrder = []; 
		parentNode.eachChild(function(node){
			childsOrder.push(node.getId());
		},this);

		 Ext.Ajax.request({
			 	url:this.controllerUrl + 'sort',
				method: 'post',
				params:{
			 			'id':data.records[0].get('id'),
			 			'newparent':parentId,
			 			'order[]' : childsOrder
			 	},
		        success: function(response, request) {
					response =  Ext.JSON.decode(response.responseText);
					if(response.success){				
						 return;
					}else{
						Ext.Msg.alert(appLang.MESSAGE, response.msg);
					}	
		      },
		      failure: app.formFailure
		});
	}
	
});